package fr.efrei.tradesys.struts.actions.admin;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fr.efrei.tradesys.hibernate.beans.AppUser;
import fr.efrei.tradesys.hibernate.beans.Currency;
import fr.efrei.tradesys.hibernate.factory.DaoFactory;

public class EditUserEndAction extends ActionSupport
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;
	private static Log				LOGGER						= LogFactory
																									.getLog(EditUserEndAction.class);
	private String						login;
	private AppUser						u;
	private String						code;
	private List<Currency>		currencies;

	@SuppressWarnings("unchecked")
	public String execute() throws Exception
	{
		LOGGER.info("Execution of " + this.getClass().getName());
		if ((login == null) || (login.compareTo("") == 0))
			return ERROR;
		// Profile update
		u.setEnabled(true);
		// Set the favorite currency
		u.setFavoriteCurrency(DaoFactory.getInstance().getCurrencyDao()
				.getCurrency(code));
		DaoFactory.getInstance().getAppUserDao().updateAppUser(u);
		Map<String, Object> session = ActionContext.getContext().getSession();
		AppUser sessionUser = (AppUser) session.get("user");
		if (sessionUser.getLogin().equals(u.getLogin()))
		{
			session.put("user", u);
		}
		addActionMessage("The profile of " + u.getLogin() + " has been updated.");
		currencies = DaoFactory.getInstance().getCurrencyDao().getAllCurrency();
		Comparator<Currency> currencyCompName = new BeanComparator("name");
		Collections.sort(currencies, currencyCompName);
		return SUCCESS;
	}

	public String getLogin()
	{
		return login;
	}

	public void setLogin(String login)
	{
		this.login = login;
	}

	public AppUser getU()
	{
		return u;
	}

	public void setU(AppUser u)
	{
		this.u = u;
	}

	public String getCode()
	{
		return code;
	}

	public void setCode(String code)
	{
		this.code = code;
	}

	public List<Currency> getCurrencies()
	{
		return currencies;
	}

	public void setCurrencies(List<Currency> currencies)
	{
		this.currencies = currencies;
	}

}
